package com.ssy.lingxi.platform.template.service.serviceimpl.adorn;

import cn.hutool.core.collection.CollectionUtil;
import com.querydsl.core.BooleanBuilder;
import com.querydsl.jpa.impl.JPAQueryFactory;
import com.ssy.lingxi.common.constant.product.PriceTypeEnum;
import com.ssy.lingxi.common.model.dto.UserLoginCacheDTO;
import com.ssy.lingxi.common.response.PageData;
import com.ssy.lingxi.common.response.ResponseCode;
import com.ssy.lingxi.common.response.Wrapper;
import com.ssy.lingxi.platform.template.service.constant.CommonBooleanEnum;
import com.ssy.lingxi.platform.template.service.constant.SelectStatusEnum;
import com.ssy.lingxi.platform.template.service.entity.adorn.*;
import com.ssy.lingxi.platform.template.service.entity.door.MemberShop;
import com.ssy.lingxi.platform.template.service.entity.door.QMemberShop;
import com.ssy.lingxi.platform.template.service.model.bo.ColumnBO;
import com.ssy.lingxi.platform.template.service.model.dto.adorn.*;
import com.ssy.lingxi.platform.template.service.model.dto.common.TemplateIdDTO;
import com.ssy.lingxi.platform.template.service.model.dto.web.RecommendDTO;
import com.ssy.lingxi.platform.template.service.model.vo.adorn.*;
import com.ssy.lingxi.platform.template.service.repository.*;
import com.ssy.lingxi.platform.template.service.service.adorn.WebEnterpriseService;
import com.ssy.lingxi.search.api.feign.ITemplateFeign;
import com.ssy.lingxi.search.api.model.request.TemplateCommoditySearchRequest;
import com.ssy.lingxi.search.api.model.response.BrandResponse;
import com.ssy.lingxi.search.api.model.response.CategoryResponse;
import com.ssy.lingxi.search.api.model.response.CommoditySearchResponse;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 模板装修 - WEB企业商城装修 - 业务实现层
 *
 * @author fhj
 * @version 2.0.0
 * @date 2020/12/15
 */
@Slf4j
@Service
public class WebEnterpriseServiceImpl implements WebEnterpriseService {

    @Resource
    private JdbcTemplate jdbcTemplate;
    @Resource
    private AdvertRepository advertRepository;
    @Resource
    private PageTemplateCategoryRepository pageTemplateCategoryRepository;
    @Resource
    private PageTemplateBrandRepository pageTemplateBrandRepository;
    @Resource
    private PageTemplateShopRepository pageTemplateShopRepository;
    @Resource
    private PageTemplateGoodsRepository pageTemplateGoodsRepository;
    @Resource
    private ITemplateFeign templateFeign;
    @Resource
    private MemberShopRepository memberShopRepository;
    @Resource
    private PageTemplateColumnRepository pageTemplateColumnRepository;
    @Resource
    private PageTemplateRepository pageTemplateRepository;
    @Resource
    private PageTemplateFirstCategoryRepository pageTemplateFirstCategoryRepository;
    @Resource
    private JPAQueryFactory jpaQueryFactory;

    /**
     * 如果请求来源是WEB企业商城且非游客身份进入时需要按登录人身份来展示不同商品价格（价格策略）
     */
    @Override
    @ApiOperation(value = "平台品类的装修内容")
    public Wrapper<CategoryAdornVO> categoryAdorn(CategoryAdornDTO dto, UserLoginCacheDTO user) {
        //定义返回实体类
        CategoryAdornVO vo = new CategoryAdornVO();

        //根据模板ID获取模板
        PageTemplate pageTemplate = pageTemplateRepository.findById(dto.getTemplateId()).orElse(new PageTemplate());

        //封装店铺数量。调用搜索服务 -> 通过品类查询会员信息接口, 再根据会员ID集合去查询店铺数量。
        Wrapper<List<Long>> getMemberIdListWrapper = templateFeign.getMemberIdByCategory(pageTemplate.getShopId(), dto.getCategoryId());
        if (getMemberIdListWrapper.getCode() != ResponseCode.SUCCESS.getCode()) {
            log.info("请求搜索服务失败:{}", getMemberIdListWrapper.getMessage());
            return Wrapper.fail(ResponseCode.SERVICE_SEARCH_ERROR);
        }
        vo.setShopNum(memberShopRepository.countByMemberIdIn(getMemberIdListWrapper.getData()));

        //封装商品数量。调用搜索服务 -> 查询商品信息接口, 拿到商品的总数。（分页参数无所谓, 目的是要拿到总记录数）
        TemplateCommoditySearchRequest request = new TemplateCommoditySearchRequest();
        request.setCurrent(1);
        request.setPageSize(1);
        request.setShopId(pageTemplate.getShopId());
        request.setCategoryId(dto.getCategoryId());
        request.setPriceTypeList(Stream.of(PriceTypeEnum.Cash.getCode()).collect(Collectors.toList()));
        request.setProvinceCode(dto.getProvinceCode());
        request.setCityCode(dto.getCityCode());
        Wrapper<PageData<CommoditySearchResponse>> goodsTotalNumWrapper = templateFeign.searchCommodityList(request);
        if (goodsTotalNumWrapper.getCode() != ResponseCode.SUCCESS.getCode()) {
            log.info("请求搜索服务失败:{}", goodsTotalNumWrapper.getMessage());
            return Wrapper.fail(ResponseCode.SERVICE_SEARCH_ERROR);
        }
        vo.setGoodsNum(goodsTotalNumWrapper.getData() != null ? goodsTotalNumWrapper.getData().getTotalCount() : 0L);

        //封装3号广告
        vo.setThirdAdvertList(advertRepository.findByTemplateIdAndCategoryIdAndType(dto.getTemplateId(), dto.getCategoryId(), 3));

        //封装二级平台品类、品类广告图
        PageTemplateCategory pageTemplateCategory = pageTemplateCategoryRepository.findByTemplateIdAndCategoryId(dto.getTemplateId(), dto.getCategoryId());
        if (pageTemplateCategory != null) {
            vo.setCategoryAdvertPicUrl(pageTemplateCategory.getAdvertPicUrl());
            vo.setIsShow(pageTemplateCategory.getIsShow());
            if (CollectionUtil.isNotEmpty(pageTemplateCategory.getTwoCategoryIds())) {
                Wrapper<List<CategoryResponse>> wrapper = templateFeign.getSecondCategoryListByMemberId(pageTemplate.getShopId(), null, null, pageTemplateCategory.getCategoryId());
                if (wrapper.getCode() != ResponseCode.SUCCESS.getCode()) {
                    log.info("请求搜索服务失败:{}", wrapper.getMessage());
                    return Wrapper.fail(ResponseCode.SERVICE_SEARCH_ERROR);
                }
                if (CollectionUtil.isNotEmpty(wrapper.getData())) {
                    vo.setCategoryBOList(
                            wrapper.getData().stream()
                                    .filter(c1 -> pageTemplateCategory.getTwoCategoryIds().stream().anyMatch(c2 -> c2.equals(c1.getId())))
                                    .map(c3 -> {
                                        CategoryVO categoryVO = new CategoryVO();
                                        categoryVO.setCategoryId(c3.getId());
                                        categoryVO.setCategoryName(c3.getName());
                                        categoryVO.setSelectStatus(CommonBooleanEnum.YES.getCode());
                                        return categoryVO;
                                    }).collect(Collectors.toList())
                    );
                }
            }
        }

        //封装商品
        PageTemplateGoods pageTemplateGoods = pageTemplateGoodsRepository.findByTemplateIdAndCategoryId(dto.getTemplateId(), dto.getCategoryId());
        if (pageTemplateGoods != null && CollectionUtil.isNotEmpty(pageTemplateGoods.getGoodsIds())) {
            TemplateCommoditySearchRequest searchRequest = new TemplateCommoditySearchRequest();
            searchRequest.setCurrent(1);
            searchRequest.setPageSize(10);
            searchRequest.setShopId(pageTemplate.getShopId());
            searchRequest.setCategoryId(dto.getCategoryId());
            searchRequest.setLoginMemberId(user != null ? user.getMemberId() : null);
            searchRequest.setLoginMemberRoleId(user != null ? user.getMemberRoleId() : null);
            searchRequest.setIdInList(pageTemplateGoods.getGoodsIds());
            searchRequest.setPriceTypeList(Stream.of(PriceTypeEnum.Cash.getCode()).collect(Collectors.toList()));
            searchRequest.setProvinceCode(dto.getProvinceCode());
            searchRequest.setCityCode(dto.getCityCode());
            Wrapper<PageData<CommoditySearchResponse>> wrapper = templateFeign.searchCommodityList(searchRequest);
            if (wrapper.getCode() != ResponseCode.SUCCESS.getCode()) {
                log.info("请求搜索服务失败:{}", wrapper.getMessage());
                return Wrapper.fail(ResponseCode.SERVICE_SEARCH_ERROR);
            }
            if (wrapper.getData() != null) {
                List<CommoditySearchResponse> templateResponseList = wrapper.getData().getData();
                if (CollectionUtil.isNotEmpty(templateResponseList)) {
                    //筛选有效的商品ID（装修时选择的商品有可能被商家进行下架或删除, 只展示上架的商品）
                    List<Long> goodsIds = pageTemplateGoods.getGoodsIds().stream()
                            .filter(a -> templateResponseList.stream().map(CommoditySearchResponse::getId).collect(Collectors.toList()).contains(a))
                            .collect(Collectors.toList());

                    //根据有效的商品ID集合来排序当前商品集合
                    List<CommoditySearchResponse> result = new ArrayList<>();
                    for (int i = 0; i < templateResponseList.size(); i++) {
                        result.add(new CommoditySearchResponse());
                    }
                    for (CommoditySearchResponse templateResponse : templateResponseList) {
                        result.set(goodsIds.indexOf(templateResponse.getId()), templateResponse);
                    }

                    //拼装
                    vo.setGoodsBOList(
                            result.stream().map(goods -> {
                                GoodsVO goodsVO = new GoodsVO();
                                goodsVO.setGoodsId(goods.getId());
                                goodsVO.setGoodsName(goods.getName());
                                goodsVO.setGoodsPicUrl(goods.getMainPic());
                                goodsVO.setGoodsPrice(goods.getMin().toString());
                                goodsVO.setCategoryName(goods.getCustomerCategory().getName());
                                goodsVO.setBrandName(goods.getBrand() != null ? goods.getBrand().getName() : null);
                                goodsVO.setMemberId(goods.getMemberId());
                                goodsVO.setMemberRoleId(goods.getMemberRoleId());
                                goodsVO.setShopId(goods.getStoreId());
                                goodsVO.setPriceType(goods.getPriceType());
                                goodsVO.setTagList(goods.getTagList());
                                return goodsVO;
                            }).collect(Collectors.toList())
                    );
                }
            }
        }

        //封装品牌
        PageTemplateBrand pageTemplateBrand = pageTemplateBrandRepository.findByTemplateIdAndCategoryId(dto.getTemplateId(), dto.getCategoryId());
        if (pageTemplateBrand != null && CollectionUtil.isNotEmpty(pageTemplateBrand.getBrandIds())) {
            Wrapper<PageData<BrandResponse>> wrapper = templateFeign.getBrandList(1, 10, pageTemplate.getShopId(), null, dto.getCategoryId(), null, null, null, null, pageTemplateBrand.getBrandIds(), null);
            if (wrapper.getCode() != ResponseCode.SUCCESS.getCode()) {
                log.info("请求搜索服务失败:{}", wrapper.getMessage());
                return Wrapper.fail(ResponseCode.SERVICE_SEARCH_ERROR);
            }
            if (wrapper.getData() != null) {
                List<BrandResponse> brandResponseList = wrapper.getData().getData();
                if (CollectionUtil.isNotEmpty(brandResponseList)) {
                    vo.setBrandBOList(
                            brandResponseList.stream().map(brand -> {
                                BrandVO brandVO = new BrandVO();
                                brandVO.setBrandId(brand.getId());
                                brandVO.setBrandLogo(brand.getLogoUrl());
                                brandVO.setBrandName(brand.getName());
                                return brandVO;
                            }).collect(Collectors.toList())
                    );
                }
            }
        }

        //封装店铺
        PageTemplateShop pageTemplateShop = pageTemplateShopRepository.findByTemplateIdAndCategoryId(dto.getTemplateId(), dto.getCategoryId());
        if (pageTemplateShop != null && CollectionUtil.isNotEmpty(pageTemplateShop.getShopIds())) {
            QMemberShop memberShop = QMemberShop.memberShop;
            BooleanBuilder builder = new BooleanBuilder();
            builder.and(memberShop.id.in(pageTemplateShop.getShopIds()));
            //搜索条件 - 省编码。
            if (StringUtils.isNotBlank(dto.getProvinceCode())) {
                builder.and(
                        memberShop.provincesCodeList.like("%" + dto.getProvinceCode() + "%")
                                .or(memberShop.provincesCodeList.eq("0"))
                );
            }
            //搜索条件 - 市编码。
            if (StringUtils.isNotBlank(dto.getCityCode())) {
                builder.and(
                        memberShop.cityCodeList.like("%" + dto.getCityCode() + "%")
                                .or(memberShop.cityCodeList.eq("0"))
                );
            }
            List<MemberShop> memberShops = jpaQueryFactory.select(memberShop).from(memberShop).where(builder).fetch();
            if (CollectionUtil.isNotEmpty(memberShops)) {
                vo.setShopBOList(
                        memberShops.stream().map(m -> {
                            ShopVO shopVO = new ShopVO();
                            shopVO.setShopId(m.getId());
                            shopVO.setShopLogo(m.getLogo());
                            shopVO.setShopName(m.getMemberName());
                            shopVO.setMemberId(m.getMemberId());
                            shopVO.setRoleId(m.getRoleId());
                            return shopVO;
                        }).collect(Collectors.toList())
                );
            }

        }

        return Wrapper.success(vo);
    }

    @Override
    @ApiOperation(value = "根据类型获取广告")
    public Wrapper<List<Advert>> findAdvertsByType(AdvertDTO dto) {
        return Wrapper.success(advertRepository.findByTemplateIdAndCategoryIdAndType(dto.getTemplateId(), dto.getCategoryId(), dto.getType()));
    }

    @Override
    @ApiOperation(value = "获取导航栏")
    public Wrapper<List<ColumnBO>> findColumn(TemplateIdDTO dto) {
        PageTemplateColumn pageTemplateColumn = pageTemplateColumnRepository.findByTemplateId(dto.getTemplateId());
        return Wrapper.success(pageTemplateColumn != null ? pageTemplateColumn.getColumnBOList() : new ArrayList<>());
    }

    @Override
    @ApiOperation(value = "获取商品列表")
    public Wrapper<PageData<GoodsVO>> findGoodsList(RecommendDTO dto) {
        //获取模板关联的商品
        PageTemplateGoods pageTemplateGoods = pageTemplateGoodsRepository.findByTemplateIdAndCategoryId(dto.getTemplateId(), dto.getCategoryId());
        List<Long> goodsIds = pageTemplateGoods != null && CollectionUtil.isNotEmpty(pageTemplateGoods.getGoodsIds()) ? pageTemplateGoods.getGoodsIds() : null;

        //根据模板ID获取模板
        PageTemplate pageTemplate = pageTemplateRepository.findById(dto.getTemplateId()).orElse(new PageTemplate());

        /*
            调用搜索服务 -> 查询商品信息接口:
               0.未选择 根据商品ID查出不包含的商品
               1.已选择 根据商品ID查出包含的商品
               2.所有  查出所有
        */
        Wrapper<PageData<CommoditySearchResponse>> wrapper = null;
        if (dto.getType().equals(SelectStatusEnum.UNSELECTED.getCode())) {
            TemplateCommoditySearchRequest searchRequest = new TemplateCommoditySearchRequest();
            searchRequest.setCurrent(dto.getCurrent());
            searchRequest.setPageSize(dto.getPageSize());
            searchRequest.setShopId(pageTemplate.getShopId());
            searchRequest.setCategoryId(dto.getTwoCategoryId() != null ? dto.getTwoCategoryId() : dto.getCategoryId());
            searchRequest.setBrandId(dto.getBrandId());
            searchRequest.setMemberName(dto.getSupplyName());
            searchRequest.setName(dto.getGoodsName());
            searchRequest.setIdNotInList(goodsIds);
            searchRequest.setPriceTypeList(Stream.of(PriceTypeEnum.Cash.getCode()).collect(Collectors.toList()));
            wrapper = templateFeign.searchCommodityList(searchRequest);
        }
        if (dto.getType().equals(SelectStatusEnum.SELECTED.getCode())) {
            if (goodsIds == null) {
                return Wrapper.success(new PageData<>(0L, new ArrayList<>()));
            }
            TemplateCommoditySearchRequest searchRequest = new TemplateCommoditySearchRequest();
            searchRequest.setCurrent(dto.getCurrent());
            searchRequest.setPageSize(dto.getPageSize());
            searchRequest.setShopId(pageTemplate.getShopId());
            searchRequest.setCategoryId(dto.getTwoCategoryId() != null ? dto.getTwoCategoryId() : dto.getCategoryId());
            searchRequest.setBrandId(dto.getBrandId());
            searchRequest.setMemberName(dto.getSupplyName());
            searchRequest.setName(dto.getGoodsName());
            searchRequest.setIdInList(goodsIds);
            searchRequest.setPriceTypeList(Stream.of(PriceTypeEnum.Cash.getCode()).collect(Collectors.toList()));
            wrapper = templateFeign.searchCommodityList(searchRequest);
        }

        //校验返回结果
        if (wrapper == null || wrapper.getData() == null || CollectionUtil.isEmpty(wrapper.getData().getData())) {
            return Wrapper.success(new PageData<>(0L, new ArrayList<>()));
        }

        //拼装
        return Wrapper.success(new PageData<>(wrapper.getData().getTotalCount(), wrapper.getData().getData().stream().map(goods -> {
            GoodsVO goodsVO = new GoodsVO();
            goodsVO.setGoodsId(goods.getId());
            goodsVO.setGoodsPicUrl(goods.getMainPic());
            goodsVO.setGoodsName(goods.getName());
            goodsVO.setGoodsSlogan(goods.getSlogan());
            goodsVO.setGoodsPoints(goods.getSellingPoint());
            goodsVO.setCategoryName(goods.getCustomerCategory().getName());
            goodsVO.setBrandName(goods.getBrand() != null ? goods.getBrand().getName() : null);
            goodsVO.setPriceRange(goods.getMin() + "~" + goods.getMax());
            goodsVO.setSupplier(goods.getMemberName());
            goodsVO.setPriceType(goods.getPriceType());
            goodsVO.setTagList(goods.getTagList());
            return goodsVO;
        }).collect(Collectors.toList())));
    }

    @Override
    @ApiOperation(value = "获取店铺列表")
    public Wrapper<PageData<ShopVO>> findShopList(RecommendDTO dto) {
        //根据模板ID获取模板
        PageTemplate pageTemplate = pageTemplateRepository.findById(dto.getTemplateId()).orElse(new PageTemplate());

        //调用搜索服务 -> 通过品类查询会员信息（平台品类关联商品，商品关联会员）。
        Wrapper<List<Long>> wrapper = templateFeign.getMemberIdByCategory(pageTemplate.getShopId(), dto.getCategoryId());
        if (wrapper.getCode() != ResponseCode.SUCCESS.getCode()) {
            log.info("请求搜索服务失败:{}", wrapper.getMessage());
            return Wrapper.fail(ResponseCode.SERVICE_SEARCH_ERROR);
        }
        if (CollectionUtil.isEmpty(wrapper.getData())) {
            return Wrapper.success(new PageData<>(0L, new ArrayList<>()));
        }

        //获取模板关联的店铺
        PageTemplateShop pageTemplateShop = pageTemplateShopRepository.findByTemplateIdAndCategoryId(dto.getTemplateId(), dto.getCategoryId());
        List<Long> shopIds = pageTemplateShop == null ? new ArrayList<>() : pageTemplateShop.getShopIds();

        //获取会员店铺信息。未选择（不包含IdNotIn）、已选择（包含IdIn），如果shopIds为空集合且又是未选择的情况，则单独查询所有。
        List<MemberShop> memberShopList;
        if (dto.getType().equals(SelectStatusEnum.UNSELECTED.getCode()) && CollectionUtil.isEmpty(shopIds)) {
            memberShopList = memberShopRepository.findAll();
        } else if (dto.getType().equals(SelectStatusEnum.UNSELECTED.getCode())) {
            memberShopList = memberShopRepository.findAllByIdNotIn(shopIds);
        } else {
            memberShopList = memberShopRepository.findAllByIdIn(shopIds);
        }

        //校验结果
        if (CollectionUtil.isEmpty(memberShopList)) {
            return Wrapper.success(new PageData<>(0L, new ArrayList<>()));
        }

        //抽取出会员ID集合, 过滤掉不属于当前这个平台品类的会员店铺。
        List<Long> memberIdList = memberShopList.stream().map(MemberShop::getMemberId).collect(Collectors.toList());
        memberIdList = memberIdList.stream().filter(id -> wrapper.getData().contains(id)).collect(Collectors.toList());
        if (CollectionUtil.isEmpty(memberIdList)) {
            return Wrapper.success(new PageData<>(0L, new ArrayList<>()));
        }

        //定义sql
        StringBuilder sbList = new StringBuilder(" SELECT ms.id shopId, ms.member_id memberId, ms.logo shopLogo, ms.member_name shopName FROM pt_member_shop ms ");
        StringBuilder sbCount = new StringBuilder(" SELECT count(ms.id) FROM pt_member_shop ms  ");

        //拼接where条件
        String where = " WHERE ms.member_id IN(" + StringUtils.join(memberIdList, ",") + ") ";
        if (StringUtils.isNotBlank(dto.getShopName())) {
            where += " AND ms.member_name Like '%" + dto.getShopName() + "%' ";
        }
        sbList.append(where);
        sbCount.append(where);

        //拼接排序与分页
        sbList.append(" ORDER BY ms.create_time DESC ");
        sbList.append(" LIMIT ").append(dto.getPageSize());
        sbList.append(" OFFSET ").append((dto.getCurrent() - 1) * dto.getPageSize());

        //获取列表数据和总记录数
        List<ShopVO> list = jdbcTemplate.query(sbList.toString(), new BeanPropertyRowMapper<>(ShopVO.class));
        Long totalCount = jdbcTemplate.queryForObject(sbCount.toString(), Long.class);

        return Wrapper.success(new PageData<>(totalCount, list));
    }

    @Override
    @ApiOperation(value = "获取品牌列表")
    public Wrapper<PageData<BrandVO>> findBrandList(RecommendDTO dto) {
        //获取模板关联的品牌
        PageTemplateBrand pageTemplateBrand = pageTemplateBrandRepository.findByTemplateIdAndCategoryId(dto.getTemplateId(), dto.getCategoryId());
        List<Long> brandIds = pageTemplateBrand != null && CollectionUtil.isNotEmpty(pageTemplateBrand.getBrandIds()) ? pageTemplateBrand.getBrandIds() : null;

        //根据模板ID获取模板
        PageTemplate pageTemplate = pageTemplateRepository.findById(dto.getTemplateId()).orElse(new PageTemplate());

        /*
            调用搜索服务 -> 查询品牌信息接口:
               0.未选择 根据品牌ID查出不包含的品牌
               1.已选择 根据品牌ID查出包含的品牌
               2.所有  查出所有
        */
        Wrapper<PageData<BrandResponse>> wrapper = null;
        if (dto.getType().equals(SelectStatusEnum.UNSELECTED.getCode())) {
            wrapper = templateFeign.getBrandList(dto.getCurrent(), dto.getPageSize(), pageTemplate.getShopId(), null, dto.getCategoryId(), null, null, null, dto.getBrandName(), null, brandIds);
        }
        if (dto.getType().equals(SelectStatusEnum.SELECTED.getCode())) {
            if (brandIds == null) {
                return Wrapper.success(new PageData<>(0L, new ArrayList<>()));
            }
            wrapper = templateFeign.getBrandList(dto.getCurrent(), dto.getPageSize(), pageTemplate.getShopId(), null, dto.getCategoryId(), null, null, null, null, brandIds, null);
        }
        if (dto.getType().equals(SelectStatusEnum.ALL.getCode())) {
            wrapper = templateFeign.getBrandList(dto.getCurrent(), dto.getPageSize(), pageTemplate.getShopId(), null, dto.getCategoryId(), null, null, null, null, null, null);
        }

        //校验返回结果
        if (wrapper == null || wrapper.getData() == null || CollectionUtil.isEmpty(wrapper.getData().getData())) {
            return Wrapper.success(new PageData<>(0L, new ArrayList<>()));
        }

        //拼装
        return Wrapper.success(new PageData<>(wrapper.getData().getTotalCount(), wrapper.getData().getData().stream().map(brand -> {
            BrandVO brandVO = new BrandVO();
            brandVO.setBrandId(brand.getId());
            brandVO.setBrandLogo(brand.getLogoUrl());
            brandVO.setBrandName(brand.getName());
            return brandVO;
        }).collect(Collectors.toList())));
    }

    @Override
    @ApiOperation(value = "获取品类列表")
    public Wrapper<CategoryAdornVO> findCategoryList(RecommendDTO dto, HttpServletRequest request) {
        //根据模板ID获取模板
        PageTemplate pageTemplate = pageTemplateRepository.findById(dto.getTemplateId()).orElse(new PageTemplate());

        //获取模板关联的品类
        PageTemplateCategory pageTemplateCategory = pageTemplateCategoryRepository.findByTemplateIdAndCategoryId(dto.getTemplateId(), dto.getCategoryId());

        //调用搜索服务 -> 根据一级平台品类获取二级平台品类
        Wrapper<List<CategoryResponse>> wrapper = templateFeign.getSecondCategoryListByMemberId(pageTemplate.getShopId(), null, null, dto.getCategoryId());
        if (wrapper.getCode() != ResponseCode.SUCCESS.getCode()) {
            log.info("请求搜索服务失败:{}", wrapper.getMessage());
            return Wrapper.fail(ResponseCode.SERVICE_SEARCH_ERROR);
        }

        //封装二级平台品类和品类广告图
        CategoryAdornVO vo = new CategoryAdornVO();
        if (CollectionUtil.isNotEmpty(wrapper.getData())) {
            vo.setCategoryBOList(
                    wrapper.getData().stream().map(a -> {
                        CategoryVO categoryVO = new CategoryVO();
                        categoryVO.setCategoryId(a.getId());
                        categoryVO.setCategoryName(a.getName());
                        categoryVO.setSelectStatus(pageTemplateCategory != null ? pageTemplateCategory.getTwoCategoryIds().contains(a.getId()) ? CommonBooleanEnum.YES.getCode() : CommonBooleanEnum.NO.getCode() : CommonBooleanEnum.NO.getCode());
                        return categoryVO;
                    }).collect(Collectors.toList())
            );
        }
        if (pageTemplateCategory != null) {
            vo.setAdvertPicUrl(pageTemplateCategory.getAdvertPicUrl());
            vo.setIsShow(pageTemplateCategory.getIsShow());
        }

        return Wrapper.success(vo);
    }

    @Override
    @Transactional
    @ApiOperation(value = "保存广告")
    public Wrapper<Void> saveAdvert(SaveAdvertDTO dto) {
        advertRepository.deleteByTemplateIdAndCategoryIdAndType(dto.getTemplateId(), dto.getCategoryId(), dto.getType());
        advertRepository.saveAll(dto.getAdverts());
        return Wrapper.success();
    }

    @Override
    @Transactional
    @ApiOperation(value = "保存导航栏")
    public Wrapper<Void> saveColumn(SaveColumnDTO dto) {
        PageTemplateColumn pageTemplateColumn = pageTemplateColumnRepository.findByTemplateId(dto.getTemplateId());
        pageTemplateColumn = pageTemplateColumn != null ? pageTemplateColumn : new PageTemplateColumn();
        pageTemplateColumn.setTemplateId(dto.getTemplateId());
        pageTemplateColumn.setColumnBOList(dto.getColumnBOList());
        pageTemplateColumnRepository.saveAndFlush(pageTemplateColumn);
        return Wrapper.success();
    }

    @Override
    @Transactional
    @ApiOperation(value = "保存商品")
    public Wrapper<Void> saveGoods(SaveTemplateAdornDTO dto) {
        PageTemplateGoods pageTemplateGoods = pageTemplateGoodsRepository.findByTemplateIdAndCategoryId(dto.getTemplateId(), dto.getCategoryId());
        pageTemplateGoods = pageTemplateGoods != null ? pageTemplateGoods : new PageTemplateGoods();
        pageTemplateGoods.setTemplateId(dto.getTemplateId());
        pageTemplateGoods.setCategoryId(dto.getCategoryId());
        pageTemplateGoods.setGoodsIds(dto.getGoodsIds());
        pageTemplateGoodsRepository.saveAndFlush(pageTemplateGoods);
        return Wrapper.success();
    }

    @Override
    @Transactional
    @ApiOperation(value = "保存店铺")
    public Wrapper<Void> saveShop(SaveTemplateAdornDTO dto) {
        PageTemplateShop pageTemplateShop = pageTemplateShopRepository.findByTemplateIdAndCategoryId(dto.getTemplateId(), dto.getCategoryId());
        pageTemplateShop = pageTemplateShop != null ? pageTemplateShop : new PageTemplateShop();
        pageTemplateShop.setTemplateId(dto.getTemplateId());
        pageTemplateShop.setCategoryId(dto.getCategoryId());
        pageTemplateShop.setShopIds(dto.getShopIds());
        pageTemplateShopRepository.saveAndFlush(pageTemplateShop);
        return Wrapper.success();
    }

    @Override
    @Transactional
    @ApiOperation(value = "保存品牌")
    public Wrapper<Void> saveBrand(SaveTemplateAdornDTO dto) {
        PageTemplateBrand pageTemplateBrand = pageTemplateBrandRepository.findByTemplateIdAndCategoryId(dto.getTemplateId(), dto.getCategoryId());
        pageTemplateBrand = pageTemplateBrand != null ? pageTemplateBrand : new PageTemplateBrand();
        pageTemplateBrand.setTemplateId(dto.getTemplateId());
        pageTemplateBrand.setCategoryId(dto.getCategoryId());
        pageTemplateBrand.setBrandIds(dto.getBrandIds());
        pageTemplateBrandRepository.saveAndFlush(pageTemplateBrand);
        return Wrapper.success();
    }

    @Override
    @Transactional
    @ApiOperation(value = "保存品类")
    public Wrapper<Void> saveCategory(SaveTemplateAdornDTO dto) {
        PageTemplateCategory pageTemplateCategory = pageTemplateCategoryRepository.findByTemplateIdAndCategoryId(dto.getTemplateId(), dto.getCategoryId());
        pageTemplateCategory = pageTemplateCategory != null ? pageTemplateCategory : new PageTemplateCategory();
        pageTemplateCategory.setTemplateId(dto.getTemplateId());
        pageTemplateCategory.setCategoryId(dto.getCategoryId());
        pageTemplateCategory.setAdvertPicUrl(dto.getCategoryAdvertPicUrl());
        pageTemplateCategory.setTwoCategoryIds(dto.getTwoCategoryIds());
        pageTemplateCategory.setIsShow(dto.getIsShow());
        pageTemplateCategoryRepository.saveAndFlush(pageTemplateCategory);
        //同时修改模板一级品类展示状态
        PageTemplateFirstCategory pageTemplateFirstCategory = pageTemplateFirstCategoryRepository.findByTemplateIdAndCategoryId(dto.getTemplateId(), dto.getCategoryId());
        if (pageTemplateFirstCategory != null) {
            pageTemplateFirstCategory.setIsShow(dto.getIsShow());
            pageTemplateFirstCategoryRepository.saveAndFlush(pageTemplateFirstCategory);
        }
        return Wrapper.success();
    }
}
